package com.etc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.etc.entity.Career;
import com.etc.entity.Role;
import com.etc.entity.RoleEquipment;
import com.etc.tools.DBTools;

public class RoleDAO {

	DBTools tool = new DBTools();
	Connection conn = tool.getConnection();
	CareerDAO careerDao = new CareerDAO();
	RoleEquipmentDAO reDao = new RoleEquipmentDAO();
	//添加一个角色
	public void addRole(Role role) {
		String sql = "insert into T_ROLE values(?,?,?,?,?,?,?,?,?,?,?)";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, role.getRoleId());
			ps.setString(2, role.getNickname());
			ps.setInt(3, role.getHeal());
			ps.setInt(4, role.getImage());
			ps.setInt(5, role.getAttack());
			ps.setInt(6, role.getCritical());
			ps.setInt(7, role.getDefense());
			ps.setInt(8, role.getSpeed());
			ps.setString(9, role.getRoleEquip().getReId());
			ps.setString(10, role.getCareer().getCareerId());
			ps.setString(11, role.getUserId());
			int confirm = ps.executeUpdate();
			if(confirm==1) System.out.println("角色添加成功");
		} catch (SQLException e) {
			System.out.println("角色添加异常");
			e.printStackTrace();
		}
	}
	//查询一个角色根据id，在下面的查询方法需要用到
	public Role findRoleById(String roleId) {
		String sql = "select * from T_ROLE where ROLE_ID = ?";
		PreparedStatement ps = null;
		Role role = null;   //一个角色需要角色装备和职业，所以下面需要创建
		RoleEquipment re = null;
		Career career = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, roleId);
			ResultSet set = ps.executeQuery();
			set.next();
			re = reDao.findREById(set.getString("re_id"));  //先根据id获取角色装备
			career = careerDao.findCareerById(set.getString("career_id")); //先根据id获取职业信息
			role = new Role(set.getString("role_id"), set.getString("nick_name"),
					set.getInt("heal"), set.getInt("image"), set.getInt("attack"),
					set.getInt("critical"), set.getInt("defense"), set.getInt("speed"),
					re, career,set.getString("user_id"));
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return role;
	}
	//登录的时候需要获取到该用户下所创建的所有角色
	//根据用户的id返回所有的角色，返回集合
	public ArrayList<Role> findAllRoleByUserId(String userId) {
		ArrayList<Role> roles = new ArrayList<>();
		String sql = "select * from t_role where USER_ID = ?";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, userId);
			ResultSet set = ps.executeQuery();
			while(set.next()) {
				Role role = findRoleById(set.getString("role_id"));
				roles.add(role);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return roles;
	}
}
